import { AssetDao } from './assetDao'
import { IncomeDao } from './incomeDao'
import { LiabilitiesDao } from './liabilitiesDao'
export class SummaryDao {
  querySummary(params: any): any {
    const date = new Date(params.date)
    // 上个月日期
    let lastMonthDate = new Date()
    lastMonthDate.setFullYear(
      date.getFullYear(),
      date.getMonth() - 1,
      1
    )
    // 当前月总资产
    let allAssetAmount: number = 0
    // 上个月总资产
    let lastAllAssetAmount: number = 0
    // 当前月总收入
    let allIncomeAmount: number = 0
    // 当前月总负债
    let allLiabilitiesAmount: number = 0
    // 上个月总负债
    let lastAllLiabilitiesAmount: number = 0
    return this.getAllAssetAmount(params).then(currentMonthAllAssetAmount => {
      return this.getAllAssetAmount({ date: lastMonthDate, creator: params.creator }).then(latMonthAllAssetAmount => {
        return new IncomeDao().queryIncomeList(params).then(IncomeListResult => {
          return this.getAllLiabilitiesAmount(params).then(currentMonthAllLiabilitiesAmount => {
            return this.getAllLiabilitiesAmount({ date: lastMonthDate, creator: params.creator }).then(latMonthAllLiabilitiesAmount => {
              for (let i = 0, len = IncomeListResult.length; i < len; i++) {
                allIncomeAmount += IncomeListResult[i].amount
              }
              allAssetAmount = currentMonthAllAssetAmount
              lastAllAssetAmount = latMonthAllAssetAmount
              allLiabilitiesAmount = currentMonthAllLiabilitiesAmount
              lastAllLiabilitiesAmount = latMonthAllLiabilitiesAmount
              // 当前月净资产
              let netAsset = allAssetAmount - allLiabilitiesAmount
              // 上个月净资产
              let lastNetAsset = lastAllAssetAmount - lastAllLiabilitiesAmount
              // 净资产变化
              let netAssetChange = netAsset - lastNetAsset
              // eslint-disable-next-line
              return {
                allAssetAmount: allAssetAmount,
                allIncomeAmount: allIncomeAmount,
                allLiabilitiesAmount: allLiabilitiesAmount,
                netAsset: netAsset,
                netAssetChange: netAssetChange,
                expenditure: allIncomeAmount - netAssetChange
              }
            })
          })
        })
      })
    })
  }
  private getAllAssetAmount(params: any): Promise<number> {
    return new AssetDao().queryFundsList(params).then(result => {
      let allAmount = 0
      for (let i = 0, len = result.length; i < len; i++) {
        allAmount += result[i].amount
      }
      return allAmount
    })
  }
  private getAllLiabilitiesAmount(params: any): Promise<any> {
    return new LiabilitiesDao().queryLiabilityList(params).then((result: any) => {
      let allAmount = 0
      for (let i = 0, len = result.length; i < len; i++) {
        allAmount += parseFloat(result[i].amount)
      }
      return allAmount
    })
  }
}
